<?
require_once dirname(__FILE__).'/BbsPdo.php';
function pr(){

	echo '<pre>';
	print_r(func_get_args());
	exit;
}
echo "<pre>\r\n";
error_reporting(E_ALL^E_NOTICE);
set_time_limit(0);
date_default_timezone_set('Asia/Shanghai');

class ImportBase{

	public function __construct(){
		$bbs_pdo=BbsPdo::get_instance();
		$this->dz_pdo=$bbs_pdo->get_dz_pdo();
		$this->bbs_pdo=$bbs_pdo->get_bbs_pdo();
		$this->ajk_pdo=$bbs_pdo->get_ajk_pdo();
	}

	public function print_msg($msg){
		$str=date("Y-m-d H:i:s").'|'.iconv('utf-8','gb2312',$msg)."\r\n";
		$handle = fopen(dirname(__FILE__)."/import_log.txt", "a+");
		fwrite($handle, $str);
		fclose($handle);
		echo $str;
	}

	public function get_user_info_from_ajk_by_userid($userid){
		if(!$userid)return false;
		$sql="select UserId,UserName,RegDate from ajk_members where UserId=?";
		$stmt=$this->ajk_pdo->prepare($sql);
		$stmt->execute(array($userid));
		$res=$stmt->fetch();
		return $res;
	}

	public function get_user_info_from_ajk($username){
		if(!$username)return false;
		$sql="select UserId,UserName,RegDate from ajk_members where UserName=?";
		$stmt=$this->ajk_pdo->prepare($sql);
		$stmt->execute(array($username));
		$res=$stmt->fetch();
		return $res;
	}

	public function get_user_id_from_bbs($username){
		if(!$username)return false;
		$sql="select id from users where username=?";
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute(array($username));
		$res=$stmt->fetch();
		if(!$res['id']){
			return false;
		}
		return $res['id'];
	}

	public function add_user_info_to_bbs($id,$username,$creation){
		$sql="insert into users set id=?,username=?,creation=?";
		$stmt = $this->bbs_pdo->prepare($sql);
        $stmt->execute(array($id,$username,$creation));
	}

	public function get_user_id($username){
		if(!$username)return false;
		if(is_numeric($this->local_cache[$username])){
			return $this->local_cache[$username];
		}
		$userid=$this->get_user_id_from_bbs($username);
		if(!$userid){
			$userinfo=$this->get_user_info_from_ajk($username);
			if($userinfo){
				$creation=date('Y-m-d H:i:s',$userinfo['RegDate']);
				$this->add_user_info_to_bbs($userinfo['UserId'],$userinfo['UserName'],$creation);
				$userid=$this->get_user_id_from_bbs($username);
			}
		}
		$this->local_cache[$username]=$userid;
		return $userid;
	}

}